package com.itelite.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itelite.common.util.SpringUtils;
import com.itelite.domain.pojo.LoginUser;
import com.itelite.handler.MyAuthenticationFailureHandler;
import com.itelite.handler.exception.VerificationCodeException;
import com.itelite.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 26-06-2021-22:08
 **/
//@Component
@Slf4j
public class VerificationCodeFilter extends OncePerRequestFilter {
    //需要传入微信获取的code
    public static final String WECHAT_FORM_USERNAME_KEY = "wechatCode";
    private final String wechatParameter = WECHAT_FORM_USERNAME_KEY;
//    @Autowired
//    private RedisService redisService;
    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        //非登陆请求不校验验证码
        if("/login".equals(request.getRequestURI())){
            try {
                verificationCode(request);
                filterChain.doFilter(request,response);
            } catch (VerificationCodeException e) {
                MyAuthenticationFailureHandler authenticationFailureHandler = SpringUtils.getBean(MyAuthenticationFailureHandler.class);
                authenticationFailureHandler.onAuthenticationFailure(request,response,e);
            }
        } else {
            filterChain.doFilter(request, response);
        }

    }
    public void verificationCode(HttpServletRequest request) throws VerificationCodeException, IOException {
        String agent = request.getHeader("User-Agent");
        //安卓免登录
        if ("okhttp/3.14.4".equals(agent)) {
            return;
        }
        String requestCode = null;
        //使用json传输
        if (request.getContentType()!=null&&request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            InputStream is = request.getInputStream();
            ObjectMapper mapper = new ObjectMapper();
            Map<String,String> jsonMap = mapper.readValue(is, Map.class);
            requestCode = jsonMap.get("captcha");
//            logger.info("jsonMap:"+jsonMap);
            LoginUser user = new LoginUser();
            user.setUsername(jsonMap.get("username"));
            user.setPassword(jsonMap.get("password"));
            String r = jsonMap.get("rememberMe")==null?"0":jsonMap.get("rememberMe");
            int t = Integer.parseInt(r);
            user.setRememberMe(t);
            request.setAttribute("jsonLoginUser",user);
        }else {
            requestCode = request.getParameter("captcha");
        }
        RedisService redisService = SpringUtils.getBean(RedisService.class);
//        logger.info("redis:"+redisService);
        String savedCode = (String) redisService.getValue(requestCode);
//        HttpSession session = request.getSession();
//        String savedCode = (String) session.getAttribute("captcha");
        if(!StringUtils.isEmpty(savedCode)){
            //不论是否验证正确，都应该将验证码清除
            redisService.removeValue(savedCode);
//            session.removeAttribute("captcha");
        }
        //校验不通过抛出异常
        if(StringUtils.isEmpty(requestCode)||StringUtils.isEmpty(savedCode)||!savedCode.equals(requestCode))
            throw new VerificationCodeException("验证码过期或验证码错误");
    }
}
